<?php

/**
 * @author Martin Pernica
 * @copyright 2008
 */

function login($log)
{
    /*
    $get_salt = Registry::get('db')->query("SELECT salt FROM ".$GLOBALS['db_prefix']."users WHERE username = '".Registry::get('db')->real_escape_string($_POST['username'])."'");
    $salt = $get_salt->fetch_array();
    */
    $hash = new Hash($_POST['username'], $_POST['password']);
    $hash->hash();
    $password = $hash->password;

    $query = Registry::get('db')->query("SELECT id, rank FROM {prefix}users WHERE username = '" . Registry::get('db')->real_escape_string($_POST['username']) .
        "' AND password = '" . $password . "'");
    if ($query->num_rows != 0) {
        $data = $query->fetch_array();
        $last_login = Registry::get('db')->query("UPDATE {prefix}users SET last_login = NOW() WHERE id = '" . intval($data['id']) . "'");
        session_regenerate_id();
        $_SESSION["logged"] = true;
        $_SESSION['id'] = $data['id'];
        $_SESSION['rank'] = $data['rank'];
        $log->write(8, 'com_user', 'NOW()', 'Creating session for user ' . $_POST['username'],
            $data['id']);
        echo '<meta http-equiv="refresh" content="2;url=' . $_SERVER['HTTP_REFERER'] .
            '">';
        Text::p(Lang::getFront('com_user', 'login_success_1'));
    } else {
        $log->write(2, 'com_user', 'NOW()', 'Login attempt failed for ' . $_POST['username'],
            0);
        Text::p(Lang::getFront('com_user', 'login_bad'));
    }
}

if (@$q[2] == "form") {
    echo '
        <h2>'.Lang::getFront('com_user', 'login_title').'</h2>
        <form id="loginForm" method="post" action="{url}index.php?q=user/login">
          <ul>
            <li><span class="username"><input type="text" id="username" name="username" value="' .
        Lang::getFront('com_user', 'username') . '" onfocus="this.value = \'\'; this.onfocus = undefined;" size="18" /></span></li>
            <li><span class="password"><input type="password" id="password" name="password" value="' .
        Lang::getFront('com_user', 'password') . '" onfocus="this.value = \'\'; this.onfocus = undefined;" size="18" /></span></li>
            <li><input type="submit" value="' . Lang::getFrontGlobal('submit') . '" /></li>
           </ul>
        </form>
        
';
} else {
    if (!empty($_POST['username']) && !empty($_POST['password'])) {
        login($log);
    } else {
        echo Lang::getFront('com_user', 'login_empty');
    }
}


?>